//package com.talent.web.pay;
//
//import cn.hutool.core.util.ObjectUtil;
//import com.talent.web.config.wx.WxPayProperties;
//import com.talent.web.enums.OrderStatus;
//import com.talent.web.enums.PayType;
//import com.talent.web.enums.ResponseEnum;
//import com.talent.web.exception.TalentException;
//import com.talent.web.model.entity.TlOrder;
//import com.talent.web.service.ITlOrderService;
//import com.wechat.pay.java.core.exception.ValidationException;
//import com.wechat.pay.java.core.notification.NotificationParser;
//import com.wechat.pay.java.core.notification.RequestParam;
//import com.wechat.pay.java.service.payments.app.AppService;
//import com.wechat.pay.java.service.payments.app.model.*;
//import com.wechat.pay.java.service.payments.model.Transaction;
//import com.wechat.pay.java.service.payments.model.TransactionAmount;
//import com.wechat.pay.java.service.payments.model.TransactionPayer;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//
//import javax.servlet.ServletInputStream;
//import javax.servlet.http.HttpServletRequest;
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//
//
///**
// * @ClassName：WxPayService
// * @Author: hszhou
// * @Date: 2025/3/27 15:18
// * @Description: 微信支付
// */
//@Service
//@RequiredArgsConstructor
//@Slf4j
//public class WxPayService {
//
//
//    private final AppService appService;
//
//    private final ITlOrderService orderService;
//
//    private final WxPayProperties wxPayProperties;
//
//    private final NotificationParser notificationParser;
//
//
//    /**
//     * 微信获取预下单
//     * @param outTradeNo 订单号
//     * @return 预订单
//     */
//    public PrepayResponse  prepay(Long outTradeNo){
//        TlOrder order = orderService.getById(outTradeNo);
//        if(ObjectUtil.isEmpty(order)){
//            throw new TalentException(ResponseEnum.ORDER_NOT_EXIT);
//        }
//        PrepayRequest request = new PrepayRequest();
//
//        request.setNotifyUrl(wxPayProperties.getNotifyUrl());
//        Amount amount = new Amount();
//        amount.setCurrency("CNY");
//        amount.setTotal(order.getPrice().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue());
//        request.setAmount(amount);
//        request.setAmount(amount);
//        request.setOutTradeNo(order.getOutTradeNo());
//        return appService.prepay(request);
//    }
//
//    /**
//     * 关闭订单
//     * @param outTradeNo 商户订单号
//     */
//    public void   closeOrder(String outTradeNo){
//
//        CloseOrderRequest request = new CloseOrderRequest();
//        request.setOutTradeNo(outTradeNo);
//        request.setMchid(wxPayProperties.getMerchantId());
//        appService.closeOrder(request);
//    }
//
//    /**
//     * 商户订单号查询订单
//     * @param outTradeNo 商户订单号
//     * @return 订单信息
//     */
//
//    public Transaction queryOrderByOutTradeNo(String outTradeNo){
//
//        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
//        request.setOutTradeNo(outTradeNo);
//        request.setMchid(wxPayProperties.getMerchantId());
//        return appService.queryOrderByOutTradeNo(request);
//    }
//
//
//    public ResponseEntity.BodyBuilder callback(HttpServletRequest request) {
//
//        String requestBody = readData(request);
//        //从请求头获取验签字段
//        //签名中的时间戳
//        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
//        //签名中的随机数
//        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
//        //应答的微信支付签名
//        String wechatSignature = request.getHeader("Wechatpay-Signature");
//        //微信支付平台证书的序列号，验签必须使用序列号对应的微信支付平台证书
//        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
//        RequestParam requestParam = new RequestParam.Builder()
//                .serialNumber(wechatPaySerial)
//                .nonce(wechatpayNonce)
//                .signature(wechatSignature)
//                .timestamp(wechatTimestamp)
//                .body(requestBody)
//                .build();
//        try {
//            // 以支付通知回调为例，验签、解密并转换成 Transaction
//            Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
//            if(transaction.getTradeState()==Transaction.TradeStateEnum.SUCCESS){
//
//                String outTradeNo = transaction.getOutTradeNo();
//                String transactionId = transaction.getTransactionId();
//                TransactionPayer payer = transaction.getPayer();
//                String openid = payer.getOpenid();
//
//                TransactionAmount amount = transaction.getAmount();
//                Integer total = amount.getTotal();
//                Integer payerTotal = amount.getPayerTotal();
//
//                orderService.updateOrder(outTradeNo,transactionId, OrderStatus.PAID, PayType.Wx);
//            }
//        } catch (ValidationException e) {
//            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
//            log.error("sign verification failed", e);
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
//        }
//        return ResponseEntity.status(HttpStatus.OK);
//    }
//
//    /**
//     * 读取请求体
//     * @param request 请求
//     * @return 请求体
//     */
//    private String readData(HttpServletRequest request) {
//
//        try {
//            ServletInputStream inputStream = request.getInputStream();
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//            // 读取请求体
//            StringBuilder sb = new StringBuilder();
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                sb.append(line);
//            }
//            return sb.toString();
//        } catch (IOException e) {
//
//            throw new RuntimeException(e);
//        }
//    }
//
//}
